import java.util.Arrays;

public class MyArrayList implements IList {
    public int usedSize;
    public int[] elem;
    public void checkPosOnAdd(int pos){
        if (pos<0||pos>usedSize){
            System.out.println("不合法");
            throw new PosIllegality("pos异常");
        }
    }
    public boolean isEmpty(){
        return this.usedSize==0;
    }
    public MyArrayList(){
        this.elem=new int[10];
    }
    public boolean isFull(){
        return this.usedSize==this.elem.length;
    }
    //如果满了,就扩容
    public  void Expansion(){
        if (isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
    }
    //新增元素,默认在数组最后新增
    @Override
    public void add(int data) {
        Expansion();
        this.elem[usedSize]=data;
        this.usedSize++;
    }

    @Override
    public void add(int pos, int data) throws PosIllegality{
        try {
            checkPosOnAdd(pos);
        }catch (PosIllegality posIllegality){
            posIllegality.printStackTrace();
            return;
        }
        Expansion();
        for(int i=usedSize-1;i>=pos;i--){
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        this.usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        if (isEmpty()){
            return false;
        }
        for (int i=0;i<usedSize;i++){
            if (elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        if(isEmpty()){
            return -1;
        }
        for (int i=0;i<usedSize;i++){
            if(elem[i]== toFind){
                return i;
            }
        }
        return -1;
    }
    private void checkPosOnGetAndSet(int pos) throws PosIllegality{
        if(pos < 0 || pos >= usedSize) {
            System.out.println("不符合法！");
            throw new PosIllegality("获取指定下标的元素异常: "+pos);
        }
    }
    @Override
    public int get(int pos) {
        checkPosOnGetAndSet(pos);

        if (isEmpty()){
            throw new MyArrayListEmpty("获取指定元素的时候"+"顺序表为空");
        }

        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        checkPosOnGetAndSet(pos);
        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int index=indexOf(toRemove);
        if(index==-1){
            System.out.println("没有这个数字");
        }
        for (int i=index+1;i<usedSize-1;i++){
            elem[i]=elem[i+1];
        }
        this.usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        this.usedSize=0;
    }

    @Override
    public void display() {
        for(int i=0;i<usedSize;i++){
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}
